<?php

namespace App\Service\Common;

use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderParam;
use Exception;
use Illuminate\Support\Facades\Log;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\InvalidArgumentException;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;

class SmsService
{
    /**
     * 短信发送配置
     *
     * @return EasySms
     */
    public function smsSendConfig(string $signName = ''): EasySms
    {
        $config = [
            // HTTP 请求的超时时间（秒）
            'timeout'  => 5.0,

            // 默认发送配置
            'default'  => [
                // 网关调用策略，默认：顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

                // 默认可用的发送网关
                'gateways' => [
                    'yunpian',
                    'aliyun',
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'aliyun' => [
                    'access_key_id'     => config('sms.accesskey_id'),
                    'access_key_secret' => config('sms.accesskey_secret'),
                    'sign_name'         => $signName ?: config('sms.sign_name'),
                ],
            ],
        ];

        return new EasySms($config);
    }

    /**
     * 阿里云短信提醒
     * @param $mobile  string  手机号
     * @param $template  string  模板编号
     * @param $data  array  变量信息
     * @throws InvalidArgumentException
     */
    public function aliyunSend($mobile, $template, $data, string $signName = '')
    {
        if (HistoryOrderParam::$importOrderMode || config('app.env') == 'dev') {
            Log::info("import Order Model aliyunSend skip... {$mobile}");
            return;
        }

        Log::info("aliyunSend", [
            'mobile'   => $mobile,
            'template' => $template,
            'data'     => $data,
        ]);

        if (mb_strlen($mobile) != 11 || !$template) {
            return;
        }

        $easySms = $this->smsSendConfig($signName);

        try {
           $easySms->send($mobile, [
                'content'  => '',
                'template' => $template,
                'data'     => $data
            ], ['aliyun']);
        } catch (NoGatewayAvailableException $exception) {

            Log::warning("aliyunSenddddddddd", [
                'mobile'   => $mobile,
                'template' => $template,
                'data'     => $data,
                'exception' => $exception->getExceptions(),
            ]);
//            throw new Exception($exception->getExceptions());
        }
    }
}
